package com.hhh.springai_test.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hhh.springai_test.common.ErrorCode;
import com.hhh.springai_test.exception.BusinessException;
import com.hhh.springai_test.model.dto.readingRoomReservation.AddReadingRoomReservationRequest;
import com.hhh.springai_test.model.dto.readingRoomReservation.UpdateReadingRoomReservationRequest;
import com.hhh.springai_test.model.po.ReadingRoom;
import com.hhh.springai_test.model.po.ReadingRoomReservation;
import com.hhh.springai_test.model.po.User;
import com.hhh.springai_test.service.ReadingRoomReservationService;
import com.hhh.springai_test.mapper.ReadingRoomReservationMapper;
import com.hhh.springai_test.service.ReadingRoomService;
import com.hhh.springai_test.service.UserService;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.ArrayList;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import org.springframework.transaction.annotation.Transactional;
import com.hhh.springai_test.model.vo.ReadingRoomReservationVO;

/**
* @author 29915
* @description 针对表【reading_room_reservation(阅览室预约记录表)】的数据库操作Service实现
* @createDate 2025-02-04 12:19:18
*/
@Service
public class ReadingRoomReservationServiceImpl extends ServiceImpl<ReadingRoomReservationMapper, ReadingRoomReservation>
    implements ReadingRoomReservationService{

    @Resource
    private ReadingRoomService readingRoomService;

    @Resource
    private UserService userService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long addReadingRoomReservation(AddReadingRoomReservationRequest addRequest,Long userId) {
        if (addRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数为空");
        }
        User user = userService.getById(userId);
        if (user == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户不存在");
        }
        Date starttime = addRequest.getStarttime();
        if (starttime == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "开始时间不能为空");
        }
        Date endtime = addRequest.getEndtime();
        if (endtime == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "结束时间不能为空");
        }
        Date date = new Date();
        if (date.after(starttime)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "开始时间不能早于当前时间");
        }
        if (endtime.before(starttime)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "结束时间不能早于开始时间");
        }
        if (starttime.after(endtime)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "开始时间不能晚于结束时间");
        }

        Long roomid = addRequest.getRoomid();
        ReadingRoom readingRoom = readingRoomService.getById(roomid);
        String openinghours = readingRoom.getOpeninghours();
        
        // 解析开放时间
        String[] parts = openinghours.split("\\|");
        if (parts.length != 2) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "阅览室开放时间格式错误");
        }
        String timeRange = parts[1];
        String[] times = timeRange.split("-");
        if (times.length != 2) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "阅览室开放时间格式错误");
        }

        // 获取开放时间的小时和分钟
        String[] openTime = times[0].split(":");
        String[] closeTime = times[1].split(":");
        
        // 设置当天的开放和关闭时间
        Calendar openCalendar = Calendar.getInstance();
        openCalendar.setTime(starttime);
        openCalendar.set(Calendar.HOUR_OF_DAY, Integer.parseInt(openTime[0]));
        openCalendar.set(Calendar.MINUTE, Integer.parseInt(openTime[1]));
        openCalendar.set(Calendar.SECOND, 0);
        
        Calendar closeCalendar = Calendar.getInstance();
        closeCalendar.setTime(starttime);
        closeCalendar.set(Calendar.HOUR_OF_DAY, Integer.parseInt(closeTime[0]));
        closeCalendar.set(Calendar.MINUTE, Integer.parseInt(closeTime[1]));
        closeCalendar.set(Calendar.SECOND, 0);

        // 检查预约时间是否在开放时间范围内
        if (starttime.before(openCalendar.getTime()) || endtime.after(closeCalendar.getTime())) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "预约时间必须在阅览室开放时间范围内");
        }
        if (readingRoom == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "阅览室不存在");
        }
        QueryWrapper<ReadingRoomReservation> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("roomId", roomid);
        queryWrapper1.eq("userId",userId);
        long count = this.count(queryWrapper1);
        if (count > 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户已经预约过该阅览室");
        }
        Integer seatnumber = addRequest.getSeatnumber();
        String seatstatus = readingRoom.getSeatstatus();
        if (seatnumber < 1 || seatnumber > 120) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "座位号不合法");
        }


        // 解析座位状态JSON并检查座位是否可用
        try {
            JSONArray seatArray = JSONArray.parseArray(seatstatus);
            // 添加座位号与座位列表长度的验证
            if (seatnumber > seatArray.size()) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "座位号超出阅览室座位总数");
            }
            
            JSONObject targetSeat = null;
            for (int i = 0; i < seatArray.size(); i++) {
                JSONObject seat = seatArray.getJSONObject(i);
                if (seat.getIntValue("number") == seatnumber) {
                    targetSeat = seat;
                    if (seat.getIntValue("status") == 0) {
                        throw new BusinessException(ErrorCode.PARAMS_ERROR, "该座位已被占用");
                    }
                    // 更新座位状态为已占用(0)
                    seat.put("status", 0);
                    break;
                }
            }
            if (targetSeat == null) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "座位号不存在");
            }
            
            // 更新阅览室的座位状态
            readingRoom.setSeatstatus(seatArray.toString());
            readingRoom.setCurrentcount(readingRoom.getCurrentcount() + 1);
            boolean updateResult = readingRoomService.updateById(readingRoom);
            if (!updateResult) {
                throw new BusinessException(ErrorCode.SYSTEM_ERROR, "更新座位状态失败");
            }
        } catch (JSONException e) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "座位状态数据格式错误");
        }

        ReadingRoomReservation reservation = new ReadingRoomReservation();
        BeanUtils.copyProperties(addRequest, reservation);
        reservation.setUserid(userId);
        // 设置初始状态为使用中
        reservation.setStatus(0);
        boolean result = this.save(reservation);
        if (!result) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "添加失败");
        }
        return reservation.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteReadingRoomReservation(Long id,Long userId) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "id不合法");
        }
        ReadingRoomReservation roomReservation = this.getById(id);
        if (roomReservation == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "该预约记录不存在");
        }
        if (!userId.equals(roomReservation.getUserid())){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "你没有权限删除该预约记录");
        }
        QueryWrapper<ReadingRoomReservation> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", id);
        queryWrapper.eq("userid", userId);
        if (this.count(queryWrapper) == 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "预约记录不存在");
        }

        // 获取预约记录和对应的阅览室信息
        ReadingRoomReservation reservation = this.getById(id);
        ReadingRoom readingRoom = readingRoomService.getById(reservation.getRoomid());
        
        // 更新座位状态
        try {
            JSONArray seatArray = JSONArray.parseArray(readingRoom.getSeatstatus());
            // 添加座位号与座位列表长度的验证
            if (reservation.getSeatnumber() > seatArray.size()) {
                throw new BusinessException(ErrorCode.SYSTEM_ERROR, "座位号超出阅览室座位总数");
            }
            
            JSONObject targetSeat = null;
            for (int i = 0; i < seatArray.size(); i++) {
                JSONObject seat = seatArray.getJSONObject(i);
                if (seat.getIntValue("number") == reservation.getSeatnumber()) {
                    // 更新座位状态为可用(1)
                    seat.put("status", 1);
                    break;
                }
            }
            
            // 更新阅览室的座位状态
            readingRoom.setSeatstatus(seatArray.toString());
            readingRoom.setCurrentcount(readingRoom.getCurrentcount() - 1);
            boolean updateResult = readingRoomService.updateById(readingRoom);
            if (!updateResult) {
                throw new BusinessException(ErrorCode.SYSTEM_ERROR, "更新座位状态失败");
            }
        } catch (JSONException e) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "座位状态数据格式错误");
        }

        // 删除预约记录
        return this.removeById(id);
    }


    @Override
    public List<ReadingRoomReservation> listReadingRoomReservation() {
        return this.list();
    }

    @Override
    public List<ReadingRoomReservationVO> getUserReservations(Long userId) {
        if (userId == null || userId <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户ID不合法");
        }

        User user = userService.getById(userId);
        if (user == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户不存在");
        }

        // 查询用户的预约记录
        QueryWrapper<ReadingRoomReservation> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userid", userId);
        queryWrapper.orderByDesc("createtime");
        List<ReadingRoomReservation> reservations = this.list(queryWrapper);
        
        // 转换为VO对象
        List<ReadingRoomReservationVO> voList = new ArrayList<>();
        for (ReadingRoomReservation reservation : reservations) {
            ReadingRoomReservationVO vo = new ReadingRoomReservationVO();
            vo.setId(reservation.getId());
            vo.setSeatNumber(reservation.getSeatnumber());
            vo.setStartTime(reservation.getStarttime());
            vo.setEndTime(reservation.getEndtime());
            
            // 获取阅览室信息
            ReadingRoom readingRoom = readingRoomService.getById(reservation.getRoomid());
            if (readingRoom != null) {
                vo.setRoomName(readingRoom.getRoomname());
            }
            
            voList.add(vo);
        }
        
        return voList;
    }
}